<template>
  <div class="bind-phone-page">
    <Header :scroll="scroll" />

    <!-- 绑定手机号内容区域 -->
    <div class="bind-phone-content">
      <div class="container">
        <div class="bind-phone-wrapper">
          <!-- 左侧品牌信息 -->
          <div class="brand-section">
            <div class="brand-content">
              <img src="@/assets/logo-full.png" alt="六堡茶" class="brand-logo" />
              <h2 class="brand-title">绑定手机号</h2>
              <p class="brand-desc">绑定手机号后，可用于登录和找回密码</p>
              <div class="features-list">
                <div class="feature-item">
                  <div class="feature-icon">📱</div>
                  <span class="feature-text">手机号登录</span>
                </div>
                <div class="feature-item">
                  <div class="feature-icon">🔒</div>
                  <span class="feature-text">找回密码</span>
                </div>
                <div class="feature-item">
                  <div class="feature-icon">🔔</div>
                  <span class="feature-text">接收通知</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧表单区域 -->
          <div class="form-section">
            <div class="form-container">
              <div class="step-content">
                <div class="form-header">
                  <h3 class="form-title">绑定手机号</h3>
                  <p class="form-subtitle">请输入您的手机号码并验证</p>
                </div>

                <el-form ref="bindPhoneFormRef" :model="bindPhoneForm" :rules="bindPhoneRules" class="bind-form">
                  <el-form-item prop="phone">
                    <el-input v-model="bindPhoneForm.phone" placeholder="请输入手机号" size="large" prefix-icon="Phone" clearable maxlength="11" />
                  </el-form-item>

                  <el-form-item prop="verifyCode">
                    <div class="verify-code-wrapper">
                      <el-input
                        v-model="bindPhoneForm.verifyCode"
                        placeholder="请输入6位验证码"
                        size="large"
                        prefix-icon="Message"
                        clearable
                        maxlength="6" />
                      <el-button class="verify-btn" :disabled="countdown > 0 || !isValidPhone(bindPhoneForm.phone)" @click="sendVerifyCode">
                        {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
                      </el-button>
                    </div>
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" size="large" class="submit-btn" :loading="loading" @click="handleBindSubmit">
                      {{ loading ? '绑定中...' : '确认绑定' }}
                    </el-button>
                  </el-form-item>
                </el-form>

                <div class="tips-section">
                  <h4 class="tips-title">温馨提示：</h4>
                  <ul class="tips-list">
                    <li>手机号绑定后可用于登录和找回密码</li>
                    <li>请确保手机号码真实有效</li>
                    <li>验证码有效期为5分钟</li>
                  </ul>
                </div>
              </div>

              <!-- 返回链接 -->
              <div class="form-footer">
                <span class="back-text">暂时不绑定？</span>
                <router-link to="/profile" class="back-link">返回个人中心</router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, reactive, onMounted, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import { useUserStore } from '@/stores/user.js'
  import apiUser from '@/api/modules/user'

  const router = useRouter()
  const userStore = useUserStore()
  const { proxy } = getCurrentInstance()
  const scroll = ref(false)
  const bindPhoneFormRef = ref()
  const loading = ref(false)
  const countdown = ref(0)

  const userInfo = computed(() => userStore.userInfo)

  // 监听滚动
  onMounted(() => {
    window.addEventListener('scroll', () => {
      scroll.value = window.scrollY > 0
    })
  })

  // 表单数据
  const bindPhoneForm = reactive({
    phone: '',
    verifyCode: '',
  })

  // 验证手机号格式
  const isValidPhone = (phone) => {
    const phoneRegex = /^1[3-9]\d{9}$/
    return phoneRegex.test(phone)
  }

  // 自定义验证函数
  const validatePhone = (rule, value, callback) => {
    if (!isValidPhone(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }

  const validateVerifyCode = (rule, value, callback) => {
    if (!value || value.length !== 6) {
      callback(new Error('验证码为6位数字'))
    } else {
      callback()
    }
  }

  // 表单验证规则
  const bindPhoneRules = {
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: validatePhone, trigger: 'blur' },
    ],
    verifyCode: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { validator: validateVerifyCode, trigger: 'blur' },
    ],
  }

  // 发送验证码
  const sendVerifyCode = async () => {
    if (!isValidPhone(bindPhoneForm.phone)) {
      ElMessage.warning('请先输入正确的手机号')
      return
    }

    try {
      // 调用发送验证码API
      // await sendSmsCode({ phone: bindPhoneForm.phone, type: 'bind_phone' })
      apiUser.GetVerifyCode({ mobile: bindPhoneForm.phone }).then(async (res) => {
        ElMessage.success('验证码已发送')
        startCountdown()
      })
    } catch (error) {
      ElMessage.error('发送失败，请重试')
    }
  }

  // 开始倒计时
  const startCountdown = () => {
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }

  // 处理绑定提交
  const handleBindSubmit = async () => {
    if (!bindPhoneFormRef.value) return

    try {
      const valid = await bindPhoneFormRef.value.validate()
      if (!valid) return

      loading.value = true

      // API调用绑定手机号
      const saveData = {
        info: {
          mobile: bindPhoneForm.phone,
        },
        verifyMobile: bindPhoneForm.phone,
        captcha: bindPhoneForm.verifyCode,
      }
      apiUser.updateUserBaseInfo(saveData).then(async (res) => {
        userInfo.value.mobile = proxy.$encryptAES(bindPhoneForm.phone)
        userInfo.value.mobile_hidden = proxy.$hidePhoneNumber(bindPhoneForm.phone)
        userStore.updateUserInfo(userInfo.value)
        ElMessage.success('手机号绑定成功！')
        // 返回个人中心
        setTimeout(() => {
          router.push('/profile')
        }, 1500)
      })
    } catch (error) {
      console.error('绑定失败:', error)
      ElMessage.error('手机号绑定失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }
</script>

<style scoped>
  .bind-phone-page {
    min-height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  }

  .bind-phone-content {
    padding: 60px 0;
    min-height: calc(100vh - 200px);
    display: flex;
    align-items: center;
  }

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }

  .bind-phone-wrapper {
    display: flex;
    background: white;
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    min-height: 600px;
  }

  /* 左侧品牌区域 */
  .brand-section {
    flex: 1;
    background: linear-gradient(135deg, #1c705e 0%, #2d8a6e 100%);
    color: white;
    padding: 60px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .brand-content {
    text-align: center;
    max-width: 400px;
  }

  .brand-logo {
    width: 120px;
    height: auto;
    margin-bottom: 30px;
  }

  .brand-title {
    font-size: 32px;
    font-weight: 600;
    margin-bottom: 16px;
  }

  .brand-desc {
    font-size: 16px;
    margin-bottom: 40px;
    opacity: 0.9;
    line-height: 1.6;
  }

  /* 功能列表 */
  .features-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .feature-item {
    display: flex;
    align-items: center;
    gap: 15px;
    opacity: 0.9;
  }

  .feature-icon {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
  }

  .feature-text {
    font-size: 14px;
    font-weight: 500;
  }

  /* 右侧表单区域 */
  .form-section {
    flex: 1;
    padding: 60px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .form-container {
    width: 100%;
    max-width: 400px;
  }

  .step-content {
    min-height: 400px;
  }

  .form-header {
    text-align: center;
    margin-bottom: 40px;
  }

  .form-title {
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }

  .form-subtitle {
    color: #666;
    font-size: 14px;
  }

  .bind-form {
    margin-bottom: 30px;
  }

  .bind-form .el-form-item {
    margin-bottom: 24px;
  }

  /* 验证码输入区域 */
  .verify-code-wrapper {
    display: flex;
    gap: 12px;
  }

  .verify-code-wrapper .el-input {
    flex: 1;
  }

  .verify-btn {
    width: 120px;
    height: 40px;
    font-size: 14px;
  }

  .submit-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 600;
    background: #1c705e;
    border-color: #1c705e;
  }

  .submit-btn:hover {
    background: #2d8a6e;
    border-color: #2d8a6e;
  }

  /* 提示区域 */
  .tips-section {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 30px;
  }

  .tips-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .tips-list {
    margin: 0;
    padding-left: 16px;
    color: #666;
    font-size: 13px;
    line-height: 1.6;
  }

  .tips-list li {
    margin-bottom: 6px;
  }

  .form-footer {
    text-align: center;
    font-size: 14px;
    color: #666;
  }

  .back-link {
    color: #1c705e;
    text-decoration: none;
    font-weight: 600;
    margin-left: 8px;
  }

  .back-link:hover {
    text-decoration: underline;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .bind-phone-wrapper {
      flex-direction: column;
      margin: 20px;
    }

    .brand-section {
      padding: 40px 20px;
    }

    .form-section {
      padding: 40px 20px;
    }

    .brand-title {
      font-size: 24px;
    }

    .form-title {
      font-size: 24px;
    }

    .features-list {
      flex-direction: row;
      justify-content: center;
      gap: 30px;
    }

    .feature-item {
      flex-direction: column;
      gap: 8px;
    }

    .feature-text {
      font-size: 12px;
    }

    .verify-code-wrapper {
      flex-direction: column;
    }

    .verify-btn {
      width: 100%;
    }
  }

  @media (max-width: 480px) {
    .bind-phone-content {
      padding: 20px 0;
    }

    .container {
      padding: 0 10px;
    }

    .brand-section,
    .form-section {
      padding: 30px 15px;
    }
  }
</style>
